package com.weido.nettyServer.utils;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

import javassist.ClassClassPath;
import javassist.ClassPool;  
import javassist.CtClass;  
import javassist.CtMethod;  
import javassist.Modifier;  
import javassist.NotFoundException;  
import javassist.bytecode.CodeAttribute;  
import javassist.bytecode.LocalVariableAttribute;  
import javassist.bytecode.MethodInfo;  
  
/**
 * 使用javassist的方法工具
 * @author rongdi
 * @date 2017年9月20日 上午11:21:29
 */
public class MethodUtil {  
  
    public static Object[] getAllParamaterName(Method method)
        throws NotFoundException {  
        Class<?> clazz = method.getDeclaringClass();  
        ClassPool pool = ClassPool.getDefault();  
        ClassClassPath classPath = new ClassClassPath(MethodUtil.class);  
        pool.insertClassPath(classPath);  
        CtClass clz = pool.get(clazz.getName());  
        CtClass[] params = new CtClass[method.getParameterTypes().length];  
        for (int i = 0; i < method.getParameterTypes().length; i++) {  
            params[i] = pool.getCtClass(method.getParameterTypes()[i].getName());  
        }  
        CtMethod cm = clz.getDeclaredMethod(method.getName(), params);  
        MethodInfo methodInfo = cm.getMethodInfo();  
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();  
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute  
            .getAttribute(LocalVariableAttribute.tag);  
        int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;  
        Object[] paramNames = new Object [cm.getParameterTypes().length];
        for (int i = 0; i < paramNames.length; i++) {  
            paramNames[i] = attr.variableName(i + pos);  
        }  
        return paramNames;  
    }  
  public static Type[] getMethodParam(Method method){
        if(method==null){
        return null;
        }
      Type[] paramTypeList = method.getGenericParameterTypes();// 方法的参数列表
      return paramTypeList;
  }
}